﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Domain.Model.Abstract
{
    public abstract class Entity
    {
        #region Properties

        private int id;
        public virtual int Id 
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        #endregion

        #region Fields

        private int? oldHashCode;

        #endregion

        #region Constructor

        public Entity()
        { 
        
        }

        #endregion

        #region Overrides

        public override int GetHashCode()
        {
            if (oldHashCode.HasValue)
                return oldHashCode.Value;

            var thisIsTransient = Equals(Id, 0);

            if (thisIsTransient)
            {
                oldHashCode = base.GetHashCode();
                return oldHashCode.Value;
            }

            return Id.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            var other = obj as Entity;

            if (other == null)
                return false;

            var otherIsTransient = Equals(other.Id, 0);
            var thisIsTransient = Equals(Id, 0);

            if (otherIsTransient && thisIsTransient)
                return ReferenceEquals(other, this);

            return other.Id.Equals(Id);
        }

        #endregion
    }
}